package com.yangming.springboot.proxy;


import com.yangming.springboot.RequirePermission;
import com.yangming.springboot.exceptions.AuthException;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.javassist.bytecode.SignatureAttribute;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.security.auth.AuthPermission;
import javax.servlet.http.HttpSession;
import java.util.List;

@Component
@EnableAspectJAutoProxy //这是切面的环绕用法
public class PermissionProxy {
    @Autowired
    private HttpSession session;


//    @Around(value = "@annotation(com.yangming.springboot.RequirePermission)")
    //但是这个注解，在我这个版本找不到，视频教程里面才有
    public Object around(MethodInvocationProceedingJoinPoint pjp) throws Throwable{
        Object result = null;
        List<String> permissions = (List<String>) session.getAttribute("permissions");
        //如果session（这个是我们与前端交互的数据缓存）如果不存在的话，直接抛出授权错误
        if (permissions == null || permissions.size() == 0){
            throw new AuthException();
        }
        //这一步是为了获取我们自定义的方法签名里面定义的code值
        //这个方法也是。这个methodSignature方法，在我这个版本里面没有，无法使用，直接报错
//        MapperMethod.MethodSignature methodSignature = (MapperMethod.MethodSignature) pjp.getSignature();
        //这一步就能拿到当前注解啦
        RequirePermission requirePermission =  methodSignature.getMethod().getDeclareAnnotation(RequirePermission.class);
        if(!permissions.contains(requirePermission.code())){
            throw new AuthException();
        }


        result = pjp.proceed();
        return result;
    }
}
